package com.xjzd.std.concurrency;

public class Print123WithWaitNotify {

    private static final Object lock = new Object();
    private static int order = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
           for (int i = 0; i < 10;) {
               synchronized (lock) {
                   if (order == 1) {
                       System.out.print("i");
                       ++i;
                       order = 2;
                       lock.notifyAll();
                   } else {
                       try {
                           lock.wait();
                       } catch (InterruptedException e) {
                           throw new RuntimeException(e);
                       }
                   }
               }
           }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10;) {
                synchronized (lock) {
                    if (order == 2) {
                        System.out.print("j");
                        ++i;
                        order = 3;
                        lock.notifyAll();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        Thread t3 = new Thread(() -> {
            for (int i = 0; i < 10;) {
                synchronized (lock) {
                    if (order == 3) {
                        System.out.println("k");
                        ++i;
                        order = 1;
                        lock.notifyAll();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
